import { history } from 'umi';
import { message } from 'antd';
import api from '../../../services';
const { queryAllUser, addUser, updateUserStatus, delUser, resetPwd } = api;

export default {
    namespace: 'userManage',

    state: {
        userList: [],
    },

    subscriptions: {
        setupHistory({ dispatch, history }) {  // eslint-disable-line
            return history.listen(({ pathname, state }) => {
                if (pathname === '/manageCenter/userManage') {
                    dispatch({ type: "queryUser" });
                    return;
                }
            })
        },
    },
    effects: {
        *queryUser({ }, { put, call, select }) {
            const result = yield call(queryAllUser);
            if (result.code === 0) {
                yield put({ type: "updateState", payload: { userList: result.data } });
            }
            else {
                message.error(result.message, 1);
            }
        },
        *addUser({ payload }, { put, call, select }) {
            const result = yield call(addUser, payload);
            if (result.code === 0) {
                yield put({ type: "queryUser" });
                message.success("添加成功");
            }
            else {
                message.error(result.message, 2);
            }
        },
        *updateUserStatus({ payload }, { put, call, select }) {
            const result = yield call(updateUserStatus, payload);
            if (result.code === 0) {
                yield put({ type: "queryUser" });
                message.success("修改成功");
            }
            else {
                message.error(result.message, 3);
            }
        },
        *delUser({ payload }, { put, call, select }) {
            const result = yield call(delUser, payload);
            if (result.code === 0) {
                yield put({ type: "queryUser" });
                message.success("删除成功");
            }
            else {
                message.error(result.message, 4);
            }
        },
        *resetPwd({ payload }, { put, call, select }) {
            const result = yield call(resetPwd, payload)
            if (result.code === 0) {
                yield put({ type: "queryUser" });
                message.success("重置成功");
            }
            else {
                message.error(result.message, 5);
            }
        }
    },
    reducers: {
        updateState(state, action) {
            return { ...state, ...action.payload };
        }
    }
};